package test.net;

import static org.junit.Assert.*;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.Calendar;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;
import org.junit.Test;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.ricky.core.net.ByteBuffer;
import com.ricky.core.net.abs.Request;
import com.ricky.core.net.i.IMessageListener;
import com.ricky.core.net.i.IServerListener;
import com.ricky.core.net.msg.AMF3Context;
import com.ricky.core.net.msg.ByteContext;
import com.ricky.core.net.msg.Context;

import com.ricky.net.Connector;
import com.ricky.utils.FileUtils;
import com.ricky.utils.Utils;

import flex.messaging.io.amf.ASObject;

public class NetTet implements IMessageListener<Context<?>>,IServerListener,Runnable{

	protected static Logger log = Logger.getLogger(NetTet.class);

	public NetTet()
	{
		connectTest();
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Runnable r=new NetTet();
		r.run();
	}
	
	@Override
	public void run() {
//		connectTest();
		sendConnect();
//		sec.schedule(this,1, TimeUnit.SECONDS);
	}
	
	@SuppressWarnings("unchecked")
	public void connectTest()
	{
		DOMConfigurator.configure(System.getProperty("user.dir")+"/config/game/log4j.xml");

		sec=new ScheduledThreadPoolExecutor(1);
		
		engine=new ScriptEngineManager().getEngineByName("javascript");
		cs=new Connector("127.0.0.1", 8001);
		cs.init();
		cs.connServer.setIserverListener(this);
		cs.connServer.setIMessageListener(this);
		cs.start();
		
		String fileName=System.getProperty("user.dir")+"/config/test/netTest.js";
		
		String js=FileUtils.readUTF8File(fileName);
//		BufferedReader reader=new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/config/test/netTest.js")));;
		try {
			engine.eval(js);
		} catch (ScriptException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	
	public void sendConnect()
	{
		if(conn!=null)
		{
			Calendar  now=Calendar.getInstance();
			ASObject obj=new ASObject();
			obj.put("cmd", "Connect");
			obj.put("name", "test"+now.get(Calendar.MONTH)+""+now.get(Calendar.DAY_OF_MONTH)+""+now.get(Calendar.MINUTE)+"");//+now.get(Calendar.SECOND
			obj.put("pwb", "pwb");
			obj.put("age", 18);
			obj.put("time",System.currentTimeMillis());
			
			fcontext=new AMF3Context(obj);
			conn.sendMessage(fcontext);
			log.info("发登陆消息!"+conn.isConnected());

		}
//			conn.sendMessage(fcontext);
//			log.info("消息发送成功!"+conn.isConnected());
//		}else
//			log.info("消息发送失败!");
	}
	

	private Context<?> fcontext;
	private Connector cs;
	private Request conn;
	private ScheduledExecutorService sec;

	public ScriptEngine engine;
	
	@Override
	public void onMessageArrived(Request request,Context<?> Context) {
		cs.workQueue.submit(new Task(request,Context));
	}
	
	public class Task implements Runnable
	{
		@SuppressWarnings("unchecked")
		public void sendMsg(String json)
		{
			String js="";
			try {
				js = new  String(json.getBytes("ISO-8859-1"),"UTF-8");
			} catch (UnsupportedEncodingException e1) {
				e1.printStackTrace();
			}
			Map<String,Object> m=Utils.jsonToMap(js.toString());
			ASObject obj=new ASObject();
			for(Entry<String, Object> e: m.entrySet())
				obj.put(e.getKey(), e.getValue());

			AMF3Context fmsg=new AMF3Context(obj);
			req.sendMessage(fmsg);
		}
		
		private Context<ASObject> fc;
		private Request req;
		public Task(Request req,Context<?> fc)
		{
			this.req=req;
			this.fc=(Context<ASObject>)fc;
		}
		@Override
		public void run() {
			ASObject as=fc.getContent();
			String cmd=fc.getHead();
			AMF3Context fmsg=null;
			engine.put("req", this);
			engine.put("log", log);

			String jsAsobj=Utils.mapToJson(as);
			
			String pro="process(\""+cmd+"\","+jsAsobj+")";
			try {
				engine.eval(pro);
			} catch (ScriptException e) {
				log.error(e.getMessage(),e);
			}
		}
		
	}

	@Override
	public void onConnectionOpend(Request conn) {
		this.conn=conn;
		run();
	}

	@Override
	public void onConnectionClosed(Request conn) {
		log.info(conn+"连接关闭");
	}

	@Override
	public void onConnectionCreated(Request conn) {
		this.conn=conn;
	}


}
